<template>
  <div class="login">
    <el-row>
      <el-col :offset="8" :span="8">
        <div class="login-logo">
          <img src="../../../public/images/avatar.png" alt="" />
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8" :offset="3">
        <!-- TODO:初始化参数从商户配置文件获取,跳转到手机号码验证页，生成绑定后台帐号-->
        <el-card shadow="hover" class="login-card qrcode">
          <div class="qr">
            <wxlogin
              appid="wxadf8c2569a62c1ee"
              scope="snsapi_login"
              redirect_uri="https%3A%2F%2Fadmin.uctoo.com%2F%23%2Fwxuser"
            >
            </wxlogin>
          </div>
          <div class="footer">
            <a href="http://www.uctoo.com/">管理系统</a> @copyright 2014-2021
          </div>
        </el-card>
      </el-col>
      <el-col :span="8" :offset="2">
        <el-card shadow="hover" class="login-card">
          <el-form
            ref="loginForm"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            autocomplete="on"
            label-position="left"
          >
            <div class="title-container">
              <h3 class="title" align="center">后台管理系统</h3>
            </div>
            <h2>登 录</h2>
            <el-divider />
            <el-form-item prop="email">
              <span class="svg-container">
                邮 箱 体验帐号demo@uctoo.com 仅浏览权限
              </span>
              <el-input
                prefix-icon="el-icon-user"
                ref="email"
                v-model="loginForm.email"
                placeholder="请输入邮箱"
                name="email"
                type="text"
                tabindex="1"
                autocomplete="on"
              />
            </el-form-item>

            <el-tooltip
              v-model="capsTooltip"
              content="Caps lock is On"
              placement="right"
              manual
            >
              <el-form-item prop="password">
                <span class="svg-container">
                  密 码 demo123
                </span>
                <el-input
                  :key="passwordType"
                  prefix-icon="el-icon-lock"
                  ref="password"
                  show-password
                  v-model="loginForm.password"
                  :type="passwordType"
                  placeholder="请输入密码"
                  name="password"
                  tabindex="2"
                  autocomplete="on"
                  @keyup.native="checkCapslock"
                  @blur="capsTooltip = false"
                  @keyup.enter.native="handleLogin"
                />
              </el-form-item>
            </el-tooltip>
            <br />
            <el-button
              :loading="loading"
              type="primary"
              @click.native.prevent="useVerify"
              ><i class="el-icon-s-promotion" /> 登 录</el-button>

            <Verify
                    ref="verify"
                    :captcha-type="'blockPuzzle'"
                    :img-size="{width:'400px',height:'200px'}"
                    @success="handleLogin"
            />
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// import { validUsername } from '@/utils/validate'
import wxlogin from "vue-wxlogin";
import Verify from "./../../components/verifition/Verify";

export default {
  components: {
    wxlogin,
    Verify
  },
  name: "Login",
  data() {
    /** const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('The password can not be less than 5 digits'))
      } else {
        callback()
      }
    }*/
    return {
      loginForm: {
        email: "demo@uctoo.com",
        password: "demo123"
      },
      loginRules: {
        email: [{ required: true, type: "email", trigger: "blur" }],
        password: [{ required: true, trigger: "blur" }]
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      mode: "pop",
      captchaType: "blockPuzzle",
      imgSize: { width: '330px', height: '155px' },
    };
  },
  computed: {
    redirect_uri() {
      let location = `${window.location.origin}/#/wxuser`;
      return encodeURIComponent(location);
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.email === "") {
      this.$refs.email.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin(params) {        //verify验证码 params 返回的二次验证参数, 和登录参数一起回传给登录接口，方便后台进行二次验证
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then(() => {
              if (this.redirect) {
                this.$router.push({
                  path: "/dashboard",
                  query: Object.assign(this.otherQuery, {
                    redirect: this.redirect
                  })
                });
              } else {
                this.$router.push({
                  path: "/",
                  query: this.otherQuery
                });
              }
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    useVerify(){
      this.$refs.verify.show()
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
};
</script>

<style lang="scss">
.login .el-input .el-input__inner {
  padding-left: 35px;
}

.login .el-card {
  border-radius: 8px;
}
@media screen and (max-device-width: 1920px) {
  .login .el-card .el-button {
    position: relative;
    left: 80%;
  }
}
@media screen and (max-device-width: 600px) {
  .login .el-card .el-button {
    position: relative;
    left: 35%;
  }
}
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      height: 47px;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px inset !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
.login {
  height: 100%;
  background: url("../../../public/images/gs.png");
  background: linear-gradient(rgba(196, 102, 0, 0.2), rgba(155, 89, 182, 0.2)),
    url("../../../public/images/gs.png");
  &-logo {
    text-align: center;
  }
  &-main {
    position: relative;
  }
  .qrcode {
    .qr {
      height: 100%;
      text-align: center;
    }
    .footer {
      text-align: center;
      color: darkgrey;
      font-size: 14px;
      bottom: 10px;
    }
  }
}
.login-container {
  min-height: 100%;
  width: 100%;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
      color: #DCDFE6;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
